package com.xiaoke.utils;

import org.springframework.beans.BeanUtils;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.beans.PropertyDescriptor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

public class BeanCopyUtils {
    private BeanCopyUtils() {

    }
    /**
     * 使用Java 11新特性将源对象中非null属性值拷贝到目标对象中
     * @param source 源对象
     * @param target 目标对象
     */
    public static <A, B> void copyNonNullProperties(A source, B target) {
        Stream.of(source.getClass().getDeclaredFields())
                .filter(field -> !field.getName().equals("serialVersionUID"))
                .forEach(field -> {
                    try {
                        field.setAccessible(true);
                        Object propertyValue = field.get(source);
                        if (Objects.nonNull(propertyValue)) {
                            PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), target.getClass());
                            propertyDescriptor.getWriteMethod().invoke(target, propertyValue);
                        }
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IntrospectionException e) {
                        throw new RuntimeException(e);
                    }
                });
    }

    /**
     *
     * @param source 原对象
     * @param clazz 需要拷贝的对象
     * @return 拷贝完成的对象
     * @param <V> 泛型
     */
    public static <V> V copyBean(Object source,Class<V> clazz) {
        //创建目标对象
        V result = null;
        try {
            result = clazz.newInstance();
            //实现属性copy
            BeanUtils.copyProperties(source, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回结果
        return result;
    }

    public static <O,V> List<V> copyBeanList(List<O> list, Class<V> clazz){
        return list.stream()
                .map(o -> copyBean(o, clazz))
                .collect(Collectors.toList());
    }
}
